﻿using FreeGoo.GameEngine;
using FreeGoo.GameEngine.Renderables;
using FarseerGames.FarseerPhysics.Collisions;
using FreeGoo.GameEngine.Interfaces;

namespace FreeGoo.GameEngine
{
    public class DemoLevel5Script : IEngineScript
    {
		private bool _fired;
		private BodyRenderable _bigBall;
		private BodyRenderable _temple1;
		private Engine _engine;
        public DemoLevel5Script()
        {			
        }
		
		public static void RegisterEngineScripts(Engine engine)
		{
			engine.AddScript(new DemoLevel5Script());
		}

        public void Prepare(Engine engine)
        {
			_bigBall = engine.GetRenderableById("BigBall") as BodyRenderable;
			_temple1 = engine.GetRenderableById("Temple1") as BodyRenderable;
			_temple1.Geom.OnCollision+=CollisionOccured;
			_engine = engine;
        }

        public void UpdatePhysics()
        {
        }

        public void Unprepare()
        {
        }
		
		private bool CollisionOccured(Geom geometry1, Geom geometry2, ContactList contactList)
        {
			if(!_fired)
			{
				if (geometry1.Tag == null || !(geometry1.Tag is BodyRenderable) ||
					geometry2.Tag == null || !(geometry2.Tag is BodyRenderable))
				{
					return true;
				}

				BodyRenderable thisRenderable = geometry1.Tag as BodyRenderable;
				BodyRenderable otherRenderable = geometry2.Tag as BodyRenderable;

				if (thisRenderable==_bigBall && otherRenderable==_temple1 || otherRenderable==_bigBall && thisRenderable==_temple1)
				{
					(_engine.GetRenderableById("Temple1") as BodyRenderable).Body.Mass /= 200;
					(_engine.GetRenderableById("Temple1") as BodyRenderable).Body.MomentOfInertia /= 200;
					(_engine.GetRenderableById("Temple2") as BodyRenderable).Body.Mass /= 200;
					(_engine.GetRenderableById("Temple2") as BodyRenderable).Body.MomentOfInertia /= 200;
					(_engine.GetRenderableById("Temple3") as BodyRenderable).Body.Mass /= 200;
					(_engine.GetRenderableById("Temple3") as BodyRenderable).Body.MomentOfInertia /= 200;
					_fired=true;
				}
			
				return true;
			}

            return true;
        }
    }
}
